package com.hellomaker.redismq.starter;

import com.hellomaker.redismq.core.mq.SimpleRedisMQClient;
import com.hellomaker.redismq.starter.impl.ListenerAutoConfigure;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.*;
import org.springframework.core.annotation.Order;
import java.util.List;

@Configuration
@AutoConfigureAfter(RedisMQPropertiesConfiguration.class)
@ConditionalOnBean(RedisMQProperties.class)
@Order(1)
public class RedisMQAutoConfiguration {

    Logger logger = LoggerFactory.getLogger(RedisMQAutoConfiguration.class);

    @Bean("simpleRedisMQClient")
    @ConditionalOnClass(SimpleRedisMQClient.class)
    SimpleRedisMQClient simpleRedisMQClient(RedisMQProperties properties) {
        SimpleRedisMQClient simpleRedisMQClient = null;
        if (properties.getDatabase() == null) {
            properties.setDatabase(0);
        }
        if (!isConfig(properties.getPassword())) {
            properties.setPassword("");
        }
        try {
            logger.info(">>>>>>> redismq client start ");
            simpleRedisMQClient = new SimpleRedisMQClient(properties.getHost(), properties.getPort(), properties.getDatabase(), properties.getPassword());
            logger.info(">>>>>>> redismq client start ok >> ip={}, port={}.", properties.getHost(), properties.getPort());
            return simpleRedisMQClient;
        } catch (Exception e) {
            logger.error(">>>>>>> redismq client start failed.", e);
            throw new IllegalStateException(e);
        }
    }

    private boolean isConfig(String prop) {
        if (prop != null && !prop.equals("") && !prop.equals("null")) {
            return true;
        }
        return false;
    }


//    @Bean
//    @Order(1)
//    AutoConfigure clientConfigure() {
//        return new ClientAutoConfigure();
//    }

    @Bean
    @Order(2)
    AutoConfigure listenerAutoConfigure() {
        return new ListenerAutoConfigure();
    }

    @Bean
    @ConditionalOnClass({ConfigureProcessor.class, AutoConfigure.class})
    ConfigureProcessor configProcessor(List<AutoConfigure> configureList) {
        ConfigureProcessor configureProcessor = new ConfigureProcessor();
        configureProcessor.setConfigureList(configureList);
        return configureProcessor;
    }


}
